package com.itheima.stock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.mapper.SysRoleMapper;
import com.itheima.stock.mapper.SysUserRoleMapper;
import com.itheima.stock.pojo.SysRole;
import com.itheima.stock.service.RoleService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.PageReq;
import com.itheima.stock.vo.req.RoleUserIdReq;
import com.itheima.stock.vo.resp.PageResult;
import com.itheima.stock.vo.resp.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @ClassName RoleServiceImpl
 * @Description TODO
 * @Author 久思
 * @Date 2023/10/8 9:33
 * @Version 1.0
 **/
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询角色信息列表
     * @param pageReq
     * @return
     */
    @Override
    public R<PageResult<SysRole>> queryRoleInfo(PageReq pageReq) {
        PageHelper.startPage(pageReq.getPageNum(), pageReq.getPageSize());

        List<SysRole> roleInfoList = sysRoleMapper.findAll();

        PageInfo<SysRole> pageInfo = new PageInfo<>(roleInfoList);

        PageResult<SysRole> pageResult = new PageResult<>(pageInfo);
        return R.ok(pageResult);
    }

    /**
     * 修改用户关联的角色信息
     * @param req
     * @return
     */
    @Override
    public R<String> updateUserOrRole(RoleUserIdReq req) {
        // 使用idWorker获取id

        // 更新用户关联的角色信息
        // 1. 先删除当前用户关联的信息
        sysUserRoleMapper.delUserAssociationRoleInfo(req.getUserId());

        // 2. 将前端传过来的角色id和用户关联起来
        req.getRoleIds().stream().forEach(item -> {
            String id = String.valueOf(idWorker.nextId());
            sysUserRoleMapper
                    .insert(id,
                            String.valueOf(req.getUserId()),
                            String.valueOf(item),
                            new Date());
        });

        return R.ok("操作成功");
    }
}
